iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0
Software Development

離開C#新手村的最後試煉系列 第 27

# 試煉27 - 自訂 class 技巧3 怎麼算加減乘除

  • 分享至 

  • xImage
  •  

開始試煉

自訂class 怎麼算加減乘除
首先 先來自訂class

void Main()
{
    var gil1 = new Gil(50);
    var gil2 = new Gil(25);
    (gil1 + gil2).ToString().Dump("gil1 + gil2");
    (gil1 - gil2).ToString().Dump("gil1 - gil2");
    (gil1 * gil2).ToString().Dump("gil1 * gil2");
    (gil1 / gil2).ToString().Dump("gil1 / gil2");
}
public class Gil
{
    public int Amount { get; set; }
    public string CurrencyName { get; } = "GD";
    public Gil(int amount)
    {
        Amount = amount;
    }
    public override string ToString() => $"{Amount} {CurrencyName}";
}

IDE直接噴錯
CS0019 Operator '+' cannot be applied to operands of type 'Gil' and 'Gil'

參考
運算子多載

之前技巧1 處理相等時 只有寫 operator == 跟!=
(相等的部分請看一下技巧1)
把加減乘除也補上吧

void Main()
{
    var gil1 = new Gil(50);
    var gil2 = new Gil(25);
    (gil1 + gil2).ToString().Dump("gil1 + gil2");
    (gil1 - gil2).ToString().Dump("gil1 - gil2");
    (gil1 * gil2).ToString().Dump("gil1 * gil2");
    (gil1 / gil2).ToString().Dump("gil1 / gil2");
}
public class Gil
{
    public int Amount { get; set; }
    public string CurrencyName { get; } = "GD";
    public Gil(int amount)
    {
        Amount = amount;
    }
    public override string ToString() => $"{Amount} {CurrencyName}";

    public static Gil operator +(Gil a) => a;
    public static Gil operator -(Gil a) => new Gil(-a.Amount);

    public static Gil operator +(Gil a, Gil b)
        => new Gil(a.Amount + b.Amount);

    public static Gil operator -(Gil a, Gil b)
        => a + (-b);

    public static Gil operator *(Gil a, Gil b)
        => new Gil(a.Amount * b.Amount);

    public static Gil operator /(Gil a, Gil b)
    {
        if (b.Amount == 0) throw new DivideByZeroException();

        return new Gil(a.Amount / b.Amount);
    }
}

結束試煉

加減乘除比較少用到 自訂物件跟數字相關的也不多


上一篇
# 試煉26 - 自訂 class 技巧2 怎麼比大小
下一篇
# 試煉28 - 自訂 class 技巧4 轉換
系列文
離開C#新手村的最後試煉30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言